package com.mfw.springboot.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mfw.springboot.common.DataGroupByDateDTO;
import com.mfw.springboot.common.ErrorCode;
import com.mfw.springboot.constant.CommonConstant;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.mapper.UserTrainingPlanRelationMapper;
import com.mfw.springboot.model.dto.userTrainingPlanRelation.UserTrainingPlanRelationQueryRequest;
import com.mfw.springboot.model.entity.TrainingPlan;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.entity.UserTrainingPlanRelation;
import com.mfw.springboot.model.vo.TrainingPlanVO;
import com.mfw.springboot.model.vo.UserTrainingPlanRelationVO;
import com.mfw.springboot.model.vo.UserVO;
import com.mfw.springboot.service.TrainingPlanService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.service.UserTrainingPlanRelationService;
import com.mfw.springboot.utils.DateUtils;
import com.mfw.springboot.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * 用户训练计划关系服务实现
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@Service
@Slf4j
public class UserTrainingPlanRelationServiceImpl extends ServiceImpl<UserTrainingPlanRelationMapper, UserTrainingPlanRelation> implements UserTrainingPlanRelationService {

    @Resource
    private UserService userService;

    @Resource
    private TrainingPlanService trainingPlanService;

    /**
     * 校验数据
     *
     * @param userTrainingPlanRelation
     * @param add                      对创建的数据进行校验
     */
    @Override
    public void validUserTrainingPlanRelation(UserTrainingPlanRelation userTrainingPlanRelation, boolean add) {
        ThrowUtils.throwIf(userTrainingPlanRelation == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long userId = userTrainingPlanRelation.getUserId();
        Long planId = userTrainingPlanRelation.getPlanId();

        // 创建数据时，参数不能为空
        if (add) {
            // 补充校验规则
            ThrowUtils.throwIf(userId == null, ErrorCode.PARAMS_ERROR);
            ThrowUtils.throwIf(planId == null, ErrorCode.PARAMS_ERROR);
        }
    }

    /**
     * 获取查询条件
     *
     * @param userTrainingPlanRelationQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<UserTrainingPlanRelation> getQueryWrapper(UserTrainingPlanRelationQueryRequest userTrainingPlanRelationQueryRequest) {
        QueryWrapper<UserTrainingPlanRelation> queryWrapper = new QueryWrapper<>();
        if (userTrainingPlanRelationQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = userTrainingPlanRelationQueryRequest.getId();
        Long userId = userTrainingPlanRelationQueryRequest.getUserId();
        Long planId = userTrainingPlanRelationQueryRequest.getPlanId();
        String status = userTrainingPlanRelationQueryRequest.getStatus();
        String sortField = userTrainingPlanRelationQueryRequest.getSortField();
        String sortOrder = userTrainingPlanRelationQueryRequest.getSortOrder();

        // 补充需要的查询条件
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(planId), "plan_id", planId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "user_id", userId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(status), "status", status);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取用户训练计划关系封装
     *
     * @param userTrainingPlanRelation
     * @param request
     * @return
     */
    @Override
    public UserTrainingPlanRelationVO getUserTrainingPlanRelationVO(UserTrainingPlanRelation userTrainingPlanRelation, HttpServletRequest request) {
        // 对象转封装类
        UserTrainingPlanRelationVO userTrainingPlanRelationVO = UserTrainingPlanRelationVO.objToVo(userTrainingPlanRelation);

        // 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = userTrainingPlanRelation.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        userTrainingPlanRelationVO.setUser(userVO);

        // 2. 关联查询训练计划信息
        Long planId = userTrainingPlanRelation.getPlanId();
        TrainingPlan trainingPlan = null;
        if (planId != null && planId > 0) {
            trainingPlan = trainingPlanService.getById(planId);
        }
        TrainingPlanVO trainingPlanVO = trainingPlanService.getTrainingPlanVO(trainingPlan, request);
        userTrainingPlanRelationVO.setTrainingPlan(trainingPlanVO);


        return userTrainingPlanRelationVO;
    }

    /**
     * 分页获取用户训练计划关系封装
     *
     * @param userTrainingPlanRelationPage
     * @param request
     * @return
     */
    @Override
    public Page<UserTrainingPlanRelationVO> getUserTrainingPlanRelationVOPage(Page<UserTrainingPlanRelation> userTrainingPlanRelationPage, HttpServletRequest request) {
        List<UserTrainingPlanRelation> userTrainingPlanRelationList = userTrainingPlanRelationPage.getRecords();
        Page<UserTrainingPlanRelationVO> userTrainingPlanRelationVOPage = new Page<>(userTrainingPlanRelationPage.getCurrent(), userTrainingPlanRelationPage.getSize(), userTrainingPlanRelationPage.getTotal());
        if (CollUtil.isEmpty(userTrainingPlanRelationList)) {
            return userTrainingPlanRelationVOPage;
        }
        // 对象列表 => 封装对象列表
        List<UserTrainingPlanRelationVO> userTrainingPlanRelationVOList = userTrainingPlanRelationList.stream().map(userTrainingPlanRelation -> {
            return UserTrainingPlanRelationVO.objToVo(userTrainingPlanRelation);
        }).collect(Collectors.toList());

        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = userTrainingPlanRelationList.stream().map(UserTrainingPlanRelation::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));

        // 2. 关联查询训练计划信息
        Set<Long> planIdSet = userTrainingPlanRelationList.stream().map(UserTrainingPlanRelation::getPlanId).collect(Collectors.toSet());
        Map<Long, List<TrainingPlan>> planIdTrainingPlanListMap = trainingPlanService.listByIds(planIdSet).stream()
                .collect(Collectors.groupingBy(TrainingPlan::getId));

        // 填充信息
        userTrainingPlanRelationVOList.forEach(userTrainingPlanRelationVO -> {
            // 1. 关联查询用户信息
            Long userId = userTrainingPlanRelationVO.getUserId();
            User user = null;
            if (userIdUserListMap.containsKey(userId)) {
                user = userIdUserListMap.get(userId).get(0);
            }
            userTrainingPlanRelationVO.setUser(userService.getUserVO(user));
            // 2. 关联查询训练计划信息
            Long planId = userTrainingPlanRelationVO.getPlanId();
            TrainingPlan trainingPlan = null;
            if (planIdTrainingPlanListMap.containsKey(planId)) {
                trainingPlan = planIdTrainingPlanListMap.get(planId).get(0);
            }
            userTrainingPlanRelationVO.setTrainingPlan(trainingPlanService.getTrainingPlanVO(trainingPlan, request));
        });
        // endregion

        userTrainingPlanRelationVOPage.setRecords(userTrainingPlanRelationVOList);
        return userTrainingPlanRelationVOPage;
    }

    /**
     * 分按日期分组查询用户训练计划关系新增数量
     *
     * @param beginDate 开始时间
     * @param endDate   结束时间
     * @return
     */
    @Override
    public List<DataGroupByDateDTO> countByDay(Date beginDate, Date endDate) {
        QueryWrapper<UserTrainingPlanRelation> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("DATE_FORMAT(create_time, '%Y-%m-%d') AS day", "COUNT(1) AS num");
        queryWrapper.ge("create_time", beginDate);
        queryWrapper.le("create_time", endDate);
        queryWrapper.groupBy("day");
        queryWrapper.orderByAsc("day");
        // 执行查询
        List<Map<String, Object>> results = this.baseMapper.selectMaps(queryWrapper);
        // 映射到 DataGroupByDateDTO
        return results.stream().map(result -> {
            DataGroupByDateDTO dto = new DataGroupByDateDTO();
            dto.setDay(DateUtils.parse(result.get("day").toString(), DateUtils.FMT_YMD));
            dto.setNum((Long) result.get("num"));
            return dto;
        }).collect(Collectors.toList());
    }

}
